/**
 * @Title: HttpClientHelperForBsn.java.
 * @Package com.transfar.inters.modules.invoke.bsnSgw.bssClientNew
 * Copyright: Copyright (c) 2014-10-22
 * Company:湖南创发科技有限责任公司
 * @author ycg
 * @date 2014-10-22 下午2:39:36
 * @version V1.0
 */
package cn.js189.uqc.util;

import cn.js189.common.constants.HttpConstant;
import cn.js189.common.domain.Response;
import cn.js189.common.util.exception.GlobalException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * <p>Class Name: HttpClientHelperForBsn.</p>
 * <p>Description: 类功能说明</p>
 * <p>Sample: 该类的典型使用方法和用例</p>
 * <p>Author: conggao</p>
 * <p>Date: 2014-10-22</p>
 * <p>Modified History: 修改记录，格式(Name)  (Version)  (Date) (Reason & Contents)</p>
 */
public class HttpClientHelperForBsn {
    private static final  Logger logger = LoggerFactory.getLogger(HttpClientHelperForBsn.class);
    
    private HttpClientHelperForBsn(){}
    /**
     * 描述:
     *
     * @author huangrougang
     * date        2011-10-2
     * --------------------------------------------------
     * 修改人            修改日期       修改描述
     * huangrougang        2011-10-2       创建
     * modified by ji_jinliang 2011-10-2
     * --------------------------------------------------
     */
    public static String post(String jsonString, String url, Integer defaultTimeOut, String codeStr) {
        logger.info("请求url：{}",url);
        logger.info("入参：{}",jsonString);
        long callStart = System.currentTimeMillis();
        ServiceClient client = null;
        try {
            client = new ServiceClient(url, "DEFAULT_INTERFACE_USER", "12321");
            client.setConnectionTimeout(defaultTimeOut);
            client.setSoTimeout(defaultTimeOut);
            Response response = client.executeAsJson(jsonString);
            logger.debug(response.getEntityAsString(codeStr));
            return response.getEntityAsString(codeStr);
        } catch (Exception e) {
            throw new GlobalException(e.getMessage());
        } finally {
            long callEnd = System.currentTimeMillis();
            logger.debug("actionUrl:{} process time:{}", url, (callEnd - callStart));
            if (client != null) {
	            client.release();
            }
        }
    }
    
    /**
     * 描述:
     * @author 鲍伟
     * date        2019-9-5
     * --------------------------------------------------
     * 修改人            修改日期       修改描述
     * 鲍伟        2019-9-5       创建
     * --------------------------------------------------
     */
    public static String postNew(String jsonString, String url){
    	String result = "";
    	HttpPost httpPost = new HttpPost(url);
    	httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
		try ( CloseableHttpClient httpclient = HttpClientBuilder.create().build();){
			StringEntity entity = new StringEntity(jsonString, HttpConstant.UTF_ENCODING);
			httpPost.setEntity(entity);
			// 发送Post,并返回一个HttpResponse对象
			HttpResponse httpResponse = httpclient.execute(httpPost);
			// 以下两行可以得到指定的Header
			HttpEntity httpEntity = httpResponse.getEntity();
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 如果状态码为200,就是正常返回
				result = EntityUtils.toString(httpEntity,HttpConstant.UTF_ENCODING);
				logger.info("调用外部接口响应参数：{}", result);
			} else {
				logger.info("调用外部接口失败！！：HttpStatus{}", httpResponse.getStatusLine().getStatusCode());
			}
		} catch (Exception e) {
			logger.info("HttpClientHelperForBsn.postNew异常:{}",e.getMessage());
		} 
		return result;
    }

    public static String postXml(String jsonString, String url, Integer defaultTimeOut, String codeStr) {
        long callStart = System.currentTimeMillis();
        ServiceClient client = null;
        try {
            client = new ServiceClient(url, "DEFAULT_INTERFACE_USER", "12321");
            client.setConnectionTimeout(defaultTimeOut);
            client.setSoTimeout(defaultTimeOut);
            Response response = client.executeAsXml(jsonString);
            return response.getEntityAsString(codeStr);
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            long callEnd = System.currentTimeMillis();
            logger.debug("actionUrl:{} process time:{}", url, (callEnd - callStart));
            if (client != null) {
	            client.release();
            }
        }
        return "";
    }

    /**
     * 表单提交方式请求
     */
    public static String postForm(String url, Map<String, String> params, Integer defaultTimeOut) {
        // 默认的超时时间
        try(CloseableHttpClient httpclient = HttpClientBuilder.create().build()) {
        HttpPost httpPost = new HttpPost(url);
      //4.3之后，超时时间用此方法设置，早期方法会报过时
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(defaultTimeOut).setConnectTimeout(defaultTimeOut).build();
        httpPost.setConfig(requestConfig);
        List<NameValuePair> list = new ArrayList<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {// 构建表单字段内容
            String key = entry.getKey();
            String value = entry.getValue();
            list.add(new BasicNameValuePair(key, value));
        }
        String out = null;
        
            httpPost.setEntity(new UrlEncodedFormEntity(list, StandardCharsets.UTF_8));
            HttpResponse httpResponse = httpclient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                out = EntityUtils.toString(httpResponse.getEntity());
                return out;
            } else if (statusCode == 404) {
                logger.warn("actionUrl:{} not found 404!" , url);
            } else {
                logger.warn("======请求其他异常错误====={}" , statusCode);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            logger.debug("调用接口结束");
        }
        return null;
    }
}
